import {Component, EventEmitter, Input, OnInit, OnDestroy, Output} from '@angular/core';
import {NzMessageService} from 'ng-zorro-antd/message';
import {AssessPriceService} from '../../assess-price.service';
import {NzImageService} from 'ng-zorro-antd/image';
import {SelectDeviceComponent} from '../../../used-store/commidity-mamage/select-device/select-device.component';
import {NzModalService} from 'ng-zorro-antd/modal';
import {PreviewOptionImgRemarkComponent} from '../../assess/preview-option-img-remark/preview-option-img-remark.component';
import {PreviewAssessTypecopyService} from './preview-assess-typecopy.service';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {catchError, debounceTime, map, switchMap} from 'rxjs/operators';
import { CommonService } from '../../../../services-common/common.service';

// 题目
interface Question {
  id: string;
  questionName: string;
  edit: boolean;
  selectType: 0 | 1;
  isRequired: boolean;
  value: string; // 选中的值
  optionsFold: boolean; // 选项是否折叠
  show: boolean; // 选项是否可见
  options: Option[];
}

// 选项
interface Option {
  id: string; // id
  checked: boolean; // 选中状态
  optionName: string; // 选项名称
  selectAble: boolean; // 是否可选
  invalidCause: string; // 不可选理由
  used: boolean; // 是否是二手
  questionId: any; // 要跳转的题目的序号
  optionRemark: string; // 选项描述
  optionImages: []; // 选项图片
  usedPriceInfo: any;
  newPriceInfo: any;
}

@Component({
  selector: 'preview-assess-modal',
  templateUrl: './preview-assess-type.component.html',
  styleUrls: ['./preview-assess-type.component.scss']
})
export class PreviewAssessTypeCopyComponent implements OnInit, OnDestroy {
  // 显隐
  // @Input() visible = false;
  @Input() isVisible = false;
  @Input() userEvaluation: any = {};

  // 所有要预览的原始数据
  questionList: any = [];
  // 基础数据
  formData: any = {};
  // 特殊设置
  customList: any = [];
  // 基准
  baseQuestion: any;
  // 题目关联
  optionsRelationPrice: any = [];
  // 一口价
  fixedPriceList: any = [];
  // 模态框显隐
  @Output() visibleChange = new EventEmitter();

  // 副本-题目列表
  copyQuestionList: Question[] = [];
  // 副本-基础数据
  copyFormData: any = {};
  // 副本-特殊设置
  copyCustomList: any = [];
  // 副本-题目关联
  copyOptionsRelationPrice: any = [];
  // 预估价格
  assessPriceText = '';
  // 是否是准新机器 只要有一个选项是准新机，那整个用准新机的价格
  isNewDevice = false;
  // 一口价估价结果
  fixedPriceResult = {isFixedPrice: false, price: 0};

  // 机型估价详情 | 机型options
  modelId = '';
  searchChange$ = new BehaviorSubject('');
  isInputLoading = false;
  recycleModelOptions: any = [];
  // 保底价和基准价
  mABP = {
    checked: false,
    minPrice: 0,
    basePrice: 0
  };
  nzFilterOption = (): boolean => true; // 机型搜索

  constructor(
    private nzImageService: NzImageService,
    private message: NzMessageService,
    private nzModalService: NzModalService,
    private assessPriceService: AssessPriceService,
    private commonService: CommonService,
    private services: PreviewAssessTypecopyService
  ) {
  }

  ngOnInit() {
    /**
     * 机型选择防抖
     * ----------------------------------------------------------------
     */
    this.searchChange$
      .asObservable()
      .pipe(debounceTime(500))
      .subscribe((value: any) => {
        if (!value) {
          // this.recycleModelOptions = [];
          return;
        }
        this.getRecycleModelOptions(value);
      });
  }

  ngOnDestroy(): void {
    this.searchChange$.unsubscribe();
  }

  // 查询机型配置list source: 1 已配置价格
  async getRecycleModelOptions(searchName: string) {
    this.isInputLoading = true;
    const res: any = await this.services.getEditModelList({name: searchName, source: 1});
    this.isInputLoading = false;
    if (res.code === 0) {
      const {records} = res.data || {};
      this.recycleModelOptions = records || [];
    } else {
      this.message.error(res.message);
    }
  }

  // 根据机型名称查询
  async getModelEvalDetailData() {
    const params = {
      id: this.modelId,
      page: 1,
      pageSize: 10
    };
    const res: any = await this.services.getModelEvalLisData(params);
    if (res.code === 0) {
      const {records} = res.data || {};
      this.preview(records[0]);
    } else {
      this.message.error(res.message);
    }
  }

  preview(data: any) {
    this.formData = {};
    this.customList = [];
    this.optionsRelationPrice = [];
    this.questionList = [];

    this.formData.brandName = data.brandName;
    this.formData.departmentName = data.seriesName;
    this.formData.typeName = data.name;
    this.formData.templateName = data.evalName;
    this.formData.remark = data.remarks;
    this.formData.usedBasePrice = data.secondHandPrice;
    this.formData.newBasePrice = data.newPrice;
    this.baseQuestion = JSON.parse(data.modelContext).baseQuestion;
    this.questionList = JSON.parse(data.mouldContext);
    this.initData();
  }

  initData() {
    this.copyQuestionList = JSON.parse(JSON.stringify(this.questionList));
    this.baseQuestion.options.forEach((o: any) => {
      if (o.questionRelation) {
        this.customList = o.customList;
        this.optionsRelationPrice = o.questionRelation;
        this.fixedPriceList = o.fixedPrice;
      }
    });
    this.copyCustomList = JSON.parse(JSON.stringify(this.customList));
    this.copyOptionsRelationPrice = JSON.parse(JSON.stringify(this.optionsRelationPrice));

    this.copyQuestionList.forEach((q: any, index) => {
      q.options = q.options.map((o: any) => ({
        ...o,
        checked: false,
        usedPriceInfo: this.copyOptionsRelationPrice[o.id]?.usedPriceInfo,
        newPriceInfo: this.copyOptionsRelationPrice[o.id]?.newPriceInfo,
      }));
      q.optionsFold = false;
      q.show = index === 0;
    });
  }

  // 单选
  singleChecked(questionIndex: number, value: any) {
    this.copyQuestionList[questionIndex].optionsFold = true;
    // 是否要清空后面的题目选中状态
    let hide = false;
    // 是否要直接结束
    let end = false;
    this.copyQuestionList[questionIndex].options.forEach((o: any) => {
      if (o.questionId) {
        hide = true;
      }
      if (o.id === value && o.questionId === 'end') {
        end = true;
      }
    });
    if (hide) {
      // 隐藏之后的选项
      this.copyQuestionList.forEach((q: any, index) => {
        if (index > questionIndex) {
          q.show = false;
          q.optionsFold = false;
          q.value = '';
          q.options.forEach((o: any) => o.checked = false);
        }
      });
    }
    if (end) {
      this.calcPrice();
      return;
    }
    if (this.copyQuestionList[questionIndex + 1]) {
      this.copyQuestionList[questionIndex + 1].show = true;
    }
    this.copyQuestionList[questionIndex].options.forEach(o => {
      if (o.id === value && o.questionId) {
        this.copyQuestionList.forEach((q: any, index) => {
          if (index > questionIndex && index < this.copyQuestionList.findIndex((q2: any) => q2.id === o.questionId)) {
            q.show = false;
          } else if (index === this.copyQuestionList.findIndex((q2: any) => q2.id === o.questionId)) {
            q.show = true;
          }
        });
      }
    });
    this.checkNotRequired(questionIndex);
    this.calcPrice();
  }

  // 多选
  multipleChecked(questionIndex: number) {
    this.checkNotRequired(questionIndex);
    if (this.copyQuestionList[questionIndex + 1]) {
      this.copyQuestionList[questionIndex + 1].show = true;
    }
    this.calcPrice();
  }

  // 检查是否剩下的全是非必选项
  checkNotRequired(questionIndex: number) {
    this.assessPriceText = '';
    if (this.copyQuestionList.some((s, index) => s.isRequired && index > questionIndex)) {
    } else {
      this.copyQuestionList.forEach((q: any, index) => {
        if (index > questionIndex) {
          q.show = true;
        }
      });
    }
  }

  // 改变折叠状态
  changeFold(question: Question) {
    question.optionsFold = !question.optionsFold;
  }

  // 隐藏预览模态框
  hidePreviewModal() {
    // this.visible = false;
    this.visibleChange?.emit();
  }

  // 获取选中的结果名称
  getResult(question: Question) {
    if (question.selectType === 0 && question.value) {
      return question.options.filter(o => o.id === question.value)[0].optionName;
    } else if (question.selectType === 1 && question.options.some(o => o.checked)) {
      return question.options.filter(o => o.checked).map(o => o.optionName).join(',');
    }
    return '';
  }

  // 一口价计算
  fixedPriceCalc(isNewDevice: boolean, ids: any[]) {
    let result = {isFixedPrice: false, price: 0};
    this.assessPriceText = '';
    this.minLimitAndBasePrice(isNewDevice, ids);
    let copyFixedPriceList = JSON.parse(JSON.stringify(this.fixedPriceList));
    copyFixedPriceList = copyFixedPriceList.sort((a: any, b: any) => {
      let bp = 0;
      let ap = 0;
      if (isNewDevice) {
        bp = b.newPriceInfo.type === 'fixed' ? b.newPriceInfo.price : this.priceToFloor(this.mABP.basePrice, b.newPriceInfo.price);
        ap = a.newPriceInfo.type === 'fixed' ? a.newPriceInfo.price : this.priceToFloor(this.mABP.basePrice, a.newPriceInfo.price);
      }
      bp = b.usedPriceInfo.type === 'fixed' ? b.usedPriceInfo.price : this.priceToFloor(this.mABP.basePrice, b.usedPriceInfo.price);
      ap = a.usedPriceInfo.type === 'fixed' ? a.usedPriceInfo.price : this.priceToFloor(this.mABP.basePrice, a.usedPriceInfo.price);
      return bp - ap;
    });
    // tslint:disable-next-line:prefer-for-of
    for (let i = 0; i < copyFixedPriceList.length; i++) {
      const optionIds = copyFixedPriceList[i].optionRelations.map((o: any) => o.optionId);
      if (new Set([...optionIds, ...ids]).size === ids.length && ids.length >= 2) {
        console.log(copyFixedPriceList[i]);
        let price: any = 0;
        if (isNewDevice) {
          if (copyFixedPriceList[i].newPriceInfo.type === 'fixed') {
            price = copyFixedPriceList[i].newPriceInfo.price;
          } else if (copyFixedPriceList[i].newPriceInfo.type === 'percentage') {
            price = this.priceToFloor(this.mABP.basePrice, copyFixedPriceList[i].newPriceInfo.price);
          }
        } else {
          if (copyFixedPriceList[i].usedPriceInfo.type === 'fixed') {
            price = copyFixedPriceList[i].usedPriceInfo.price;
          } else if (copyFixedPriceList[i].usedPriceInfo.type === 'percentage') {
            price = this.priceToFloor(this.mABP.basePrice, copyFixedPriceList[i].usedPriceInfo.price);
          }
        }
        price = `${isNewDevice ? '准新' : '二手'}${price < this.mABP.minPrice ? '保底价格（一口价）：' : '一口价：'}${price < this.mABP.minPrice ? Math.floor(this.mABP.minPrice) : Math.floor(price)}`;
        result = {isFixedPrice: true, price};
      }
    }
    return result;
  }

  // 获取保底价格和基准价格
  minLimitAndBasePrice(isNewDevice: boolean, ids: any[]) {
    this.mABP = {
      checked: false,
      minPrice: 0,
      basePrice: 0
    };
    this.baseQuestion.options.forEach((o: any) => {
      if (ids.includes(o.id)) {
        this.mABP.checked = true;
        this.customList = o.customList;
        this.optionsRelationPrice = o.questionRelation;
        this.fixedPriceList = o.fixedPrice;
        this.copyCustomList = JSON.parse(JSON.stringify(this.customList));
        this.copyOptionsRelationPrice = JSON.parse(JSON.stringify(this.optionsRelationPrice));
        this.copyQuestionList.forEach((q: any, index) => {
          q.options.forEach((oo: any) => {
            oo.usedPriceInfo = this.copyOptionsRelationPrice[oo.id].usedPriceInfo;
            oo.newPriceInfo = this.copyOptionsRelationPrice[oo.id].newPriceInfo;
          });
        });
        if (isNewDevice) {
          this.mABP.basePrice = o.newPriceInfo.basePrice;
          if (o.newPriceInfo.type === 'fixed') {
            this.mABP.minPrice = o.newPriceInfo.price;
          } else if (o.newPriceInfo.type === 'percentage') {
            this.mABP.minPrice = this.priceToFloor(o.newPriceInfo.basePrice, o.newPriceInfo.price);
          }
        } else {
          this.mABP.basePrice = o.usedPriceInfo.basePrice;
          if (o.usedPriceInfo.type === 'fixed') {
            this.mABP.minPrice = o.usedPriceInfo.price;
          } else if (o.usedPriceInfo.type === 'percentage') {
            this.mABP.minPrice = this.priceToFloor(o.usedPriceInfo.basePrice, o.usedPriceInfo.price);
          }
        }
      }
    });
  }

  calcPrice() {
    this.isNewDevice = false;
    // 选中的选项结果id
    let ids: any[] = [];
    // 选中的多选id
    const multipleIds: any[] = [];
    // 二手基础价格
    let usedPrice = 0;
    // 准新基础价格
    let newPrice = 0;
    // 展示价格计算结果
    this.assessPriceText = '';
    const copyQuestionList = JSON.parse(JSON.stringify(this.questionList));
    // 获取选中的选项添加到ids并判断是否是准新机
    this.copyQuestionList.forEach(question => {
      if (question.selectType === 0 && question.value) {
        // 添加单选选项到ids
        ids.push(question.value);
        question.options.forEach(option => {
          if (!option.used && option.id === question.value) {
            // 判定为准新机器
            this.isNewDevice = true;
          }
        });
      } else if (question.selectType === 1) {
        // 遍历多选选项
        question.options.forEach(option => {
          // 添加多选选项到ids
          if (option.checked) {
            ids.push(option.id);
            multipleIds.push(option.id);
            if (!option.used) {
              // 判定为准新机器
              this.isNewDevice = true;
            }
          }
        });
      }
    });

    const result = this.fixedPriceCalc(this.isNewDevice, ids);
    this.fixedPriceResult = result;
    if (result.isFixedPrice) {
      return;
    }
    // 计算特殊设置扣钱金额
    const customResult: any = [];
    this.minLimitAndBasePrice(this.isNewDevice, ids);
    const copyOptionsRelationPrice = JSON.parse(JSON.stringify(this.optionsRelationPrice));
    const copyCustomList = JSON.parse(JSON.stringify(this.customList));
    if (this.isNewDevice) {
      newPrice = this.mABP.basePrice;
    } else {
      usedPrice = this.mABP.basePrice;
    }
    copyCustomList.forEach((group: any) => {
      group.forEach((c: any) => {
        if (c.newPriceInfo.type === 'fixed') {
          c.newPriceInfo.price = -c.newPriceInfo.price;
        } else if (c.usedPriceInfo.type === 'percentage') {
          c.newPriceInfo.price = -this.priceToFloor(this.mABP.basePrice, c.newPriceInfo.price);
        }
        if (c.usedPriceInfo.type === 'fixed') {
          c.usedPriceInfo.price = -c.usedPriceInfo.price;
        } else if (c.usedPriceInfo.type === 'percentage') {
          c.usedPriceInfo.price = -this.priceToFloor(this.mABP.basePrice, c.usedPriceInfo.price);
        }
      });
      group = group.sort((a: any, b: any) => {
        if (this.isNewDevice) {
          return a.newPriceInfo.price - b.newPriceInfo.price;
        }
        return a.usedPriceInfo.price - b.usedPriceInfo.price;
      });
      let first = true;
      group.forEach((c: any) => {
        if (first) {
          const options = c.optionRelations.map((o: any) => o.optionId);
          if (ids.length >= 2 && ids.length === new Set([...ids, ...options]).size) {
            first = false;
            customResult.push([c]);
          }
        }
      });
    });
    // 价格计算到结果中
    customResult.forEach((g: any) => {
      if (this.isNewDevice) {
        newPrice += g[0].newPriceInfo.price;
      } else {
        usedPrice += g[0].usedPriceInfo.price;
      }
    });
    // 剔除已经计算过特殊设置了的选项
    const customResultIds = customResult.map((g: any) => g[0].optionRelations.map((o: any) => o.optionId)).flat();
    ids = ids.filter(id => !customResultIds.includes(id) && !multipleIds.includes(id));

    const availableMultipleIds = multipleIds.filter(id => !customResultIds.includes(id));
    ids = [...ids, ...availableMultipleIds];
    ids.forEach(id => {
      // @ts-ignore
      usedPrice += copyOptionsRelationPrice[id].usedPriceInfo.type === 'fixed' ?
        -copyOptionsRelationPrice[id].usedPriceInfo.price :
        -this.priceToFloor(this.mABP.basePrice, copyOptionsRelationPrice[id].usedPriceInfo.price);
      // @ts-ignore
      newPrice += copyOptionsRelationPrice[id].newPriceInfo.type === 'fixed' ?
        -copyOptionsRelationPrice[id].newPriceInfo.price :
        -this.priceToFloor(this.mABP.basePrice, copyOptionsRelationPrice[id].newPriceInfo.price);
    });

    if (this.isNewDevice) {
      // @ts-ignore
      this.assessPriceText = `预计准新${newPrice < this.mABP.minPrice ? '保底价格：' : '价格：'}${newPrice < this.mABP.minPrice ? Math.floor(this.mABP.minPrice) : Math.floor(newPrice)}`;
    } else {
      // @ts-ignore
      this.assessPriceText = `预计二手${usedPrice < this.mABP.minPrice ? '保底价格：' : '价格：'}${usedPrice < this.mABP.minPrice ? Math.floor(this.mABP.minPrice) : Math.floor(usedPrice)}`;
    }
  }

  calcQuestionIndex(questionIndex: number) {
    return this.copyQuestionList.filter((q, index) => (q.show && index <= questionIndex)).length;
  }

  // 显示选项描述和图片
  showOptionRemarkModal(question: any, option: any, $event: any) {
    let details: any[] = [];
    question.options.forEach((o: any) => {
      if (o.optionImages || o.optionRemark) {
        details = [...details, ...o.optionImages.split(',').map((v: any) => ({
          id: o.id,
          name: o.optionName,
          url: v,
          remark: o.optionRemark
        }))];
      }
    });
    const index = details.findIndex(d => d.id === option.id);
    const modal = this.nzModalService.create({
      nzTitle: question.questionName,
      nzContent: PreviewOptionImgRemarkComponent,
      nzComponentParams: {
        details,
        index
      },
      nzFooter: null,
      nzMaskClosable: true,
    });
    $event.stopPropagation();
    $event.preventDefault();
    $event.returnValue = false;
  }

  // 查看图片
  previewImage(src: string) {
    this.nzImageService.preview([{src, width: '400px', height: '400px'}], {nzZoom: 1.5, nzRotate: 0});
  }

  // 题目id转名称
  questionIdToName(id: string, questionList: any[]) {
    let result = id === 'end' ? '结束' : 'id转名称异常';
    questionList.forEach((q: any, index) => {
      if (q.id === id) {
        result = q.questionName;
      }
    });
    return result;
  }

  // 选项id转名称
  optionIdToName(id: string) {
    let name = '';
    this.questionList.forEach((q: any) => {
      if (q.id === this.baseQuestion.questionId) {
        q.options.forEach((o: any) => {
          if (o.id === id) {
            name = o.optionName;
          }
        });
      }
    });
    return name;
  }

  // 百分比价格转换
  priceToFloor(price: any, percent = 100) {
    return price * percent / 100;
  }

  /**
   * ----------------------------------------------------------------
   * 机型选择 Select
   * ----------------------------------------------------------------
   */
  searchModel(value: any) {
    this.searchChange$.next(value);
  }

  modelChange(value: any) {
    this.assessPriceText = '';
    this.getModelEvalDetailData();
  }

  handleCancel() {
    this.formData = {};
    this.customList = [];
    this.optionsRelationPrice = [];
    this.questionList = [];
    this.fixedPriceList = null;
    this.modelId = '';
    this.assessPriceText = '';

    this.isVisible = false;
  }

  // Copy
  copyText(str: any) {
    this.commonService.copyStr(str);
  }
}
